package network.netty;

import com.sun.corba.se.internal.CosNaming.BootstrapServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import network.netty.coding.ByteToChatMessageDecoder;
import network.netty.handler.ServerChatMessageReadHandler;

/**
 * <p>
 * 基于Netty的TCP服务端
 * </p>
 *
 * @author LovelyBigDuck
 * @date 2021/5/29 17:26
 */
public class TcpNettyServer {
    public static void main(String[] args) {
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        // childHandler是对work组线程起作用,handler是对boss线程组起作用
        serverBootstrap.group(bossGroup,workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        // 添加解码器，将byte解析为对象
                        pipeline.addLast(new ByteToChatMessageDecoder());
                        // 自定义handler处理业务逻辑
                        pipeline.addLast(new ServerChatMessageReadHandler());
                    }
                });
        try {
            serverBootstrap.bind("localhost",8888).channel().closeFuture().sync();
        } catch (InterruptedException e) {
            System.out.println("服务端启动失败。。。");
            e.printStackTrace();
        }
    }
}
